<template>
  <div>
    <el-dialog :title="title" v-model="visible" width="460px" draggable>
      <el-form ref="formRef" :model="formData" label-position="right" label-width="100px">
        <el-form-item label="处理人" prop="handleUser" required>
          <el-select
            v-model="formData.handleUser"
            placeholder="请选择处理人"
            clearable
          >
            <el-option
              v-for="item in groupList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="平台类型" prop="platformType" required>
          <el-select v-model="formData.platformType">
            <el-option v-for="item in getEnumBySn('daikuanTypeEnum')" :label="item.label"
                       :key="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="平台" prop="platform" required>
          <el-input v-model="formData.platform" class="input_width"></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="trusteeshipAmount" required>
          <el-input-number v-model="formData.trusteeshipAmount"></el-input-number>
        </el-form-item>

        <el-form-item label="处理状态" prop="status" required>
          <el-select v-model="formData.status" clearable>
            <el-option v-for="item in getEnumBySn('maintenanceStatus')" :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理进度">
          <el-select v-model="formData.handleProgress" clearable
                     :disabled="formData.status!='已完成'">
            <el-option v-for="item in getEnumBySn('trusteeshipStatus')" :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-autocomplete
            v-model="formData.handleMemo"
            :fetch-suggestions="querySearch"
            clearable
            class="inline-input w-50"
            placeholder="备注"
            trigger-on-focus
          />
        </el-form-item>
        <el-form-item label="进线电话" prop="comePhone" >
          <el-select v-model="formData.comePhone" clearable filterable>
            <el-option v-for="item in comePhoneList" :key="item.id"
                       :label="item.indexId"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="平台电话" prop="platformPhone">
          <el-select v-model="formData.platformPhone" clearable filterable>
            <el-option
              v-for="item in kfPhoneList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              style="height: 60px"
            >
              <div>
                <span>{{ item.label }}</span>
                <div
                  style="
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                  margin-top: -10px;
                  "
                >
                  {{ item.desc }}
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button style="height:50px;font-size: 50px" type="primary" @click="getTrusteeshipDtlInfo">身份信息</el-button>
<!--          <el-button style="height:40px;font-size: 40px" @click="visible = false">取 消</el-button>-->
          <el-button style="height:50px;font-size: 50px" type="primary" @click="updateNativePlaceHandle">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <PersonInfo ref="personInfoRef"></PersonInfo>
  </div>
</template>

<script lang="ts" setup>
import {getEnumBySn, groupList} from "@/api/enums";
import PersonInfo from "@/views/tool/maintenance/PersonInfo.vue";


const visible = ref(false)
const formRef = ref()
const formData = ref({})
const personInfoRef = ref()

const props = defineProps({
  currentItem: {
    type: Object,
    required: true,
  },
});
import request from '@/config/axios'
import {} from "@/router/modules/remaining";
import {} from "@/router/modules/remaining";

const emit = defineEmits(["ok"])
const updateNativePlaceHandle = function () {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post({
        url: '/maintenance/updateMaintenance',
        data: formData.value,
      }).then(res => {
        visible.value = false
        emit("ok")
      })
    }
  })
}


const kfPhoneList = ref([])

const getKfPhoneList = function () {
  request.get({
    url: '/kfPhone/dict',
    params: {}
  }).then(res => {
    kfPhoneList.value = res?.map(item => {
      return {
        label: item.name + "（" + item.phoneNo + "）",
        desc: [
          `缓催政策：${item.delayPolicy || '无'}`,
          `时间：${item.serviceTime || '无'}`,
          `所需资料内容：${item.requiredInfo || '无'}`,
          `特殊网贷方案：${item.specialLoanPlan || '无'}`
        ].join('；'),
        value: item.id,
      }
    })
  })
}

getKfPhoneList()

/**
 * 获取托管详情信息
 */
const getTrusteeshipDtlInfo = function () {
  console.log('---托管明细id---', formData.value.tgDtlId)
  request.get({
    url: "/maintenance/getTrusteeshipDetailById",
    params: {
      dtlId: formData.value.tgDtlId,
    }
  }).then(res => {
    personInfoRef.value.edit(res)
  })
}

const title = ref('')

interface RestaurantItem {
  value: string
  link: string
}

const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}

const restaurants = ref<RestaurantItem[]>([])

const querySearch = function (queryString: string, cb: any){
  const results = queryString && queryString != 'null'
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  cb(results)
}

const loadAll = () => {
  return [
    { value: '1.本人不失联 不联系三方', link: '1.本人不失联 不联系三方' },
    { value: '2.屏蔽紧急联系人 降低催收频次', link: '2.屏蔽紧急联系人 降低催收频次' },
    { value: '3.只联系本人 不联系三方', link: '3.只联系本人 不联系三方' },
    { value: '4.看详情', link: '4.看详情' },
    { value: '5.等回电', link: '5.等回电' },
    { value: '6.黑猫投诉', link: '6.黑猫投诉' }
  ]
}

const allComePhoneList = ref([])
const comePhoneList = ref([])
const isPhoneListLoaded = ref(false)

//初始进线手机号下拉列表
const loadPhoneList = async () => {
  try {
    const res = await request.get({
      url: '/transferPhone/list',
    })
    allComePhoneList.value = res
    isPhoneListLoaded.value = true
    // 如果已经有当前数据，则进行过滤
    if (formData.value?.sex) {
      filterPhoneList()
    }
  } catch (error) {
    console.error('加载手机号列表失败:', error)
  }
}

// 过滤手机号列表
const filterPhoneList = () => {
  if (!isPhoneListLoaded.value || !formData.value?.sex) return
  
  comePhoneList.value = allComePhoneList.value.filter(item => 
    item.indexId?.includes(formData.value.sex) && 
    !item.indexId?.startsWith("000")
  )
}

// 在组件挂载时加载手机号列表
onMounted(() => {
  loadPhoneList()
  restaurants.value = loadAll()
})

defineExpose({
  edit: (rowData) => {
    visible.value = true
    formData.value = rowData
    title.value = rowData.customName + '---' + rowData.agencyName + '---' + rowData.phoneNo
    // 如果手机号列表已加载，则进行过滤
    if (isPhoneListLoaded.value) {
      filterPhoneList()
    }
    console.log('---托管明细id---', formData.value)
  }
})

const handleFocus = () => {
  querySearch('', (results) => {
    restaurants.value = results
  })
}
</script>


<style scoped>
.flex {
  display: flex;
}
.flex-col {
  flex-direction: column;
}
.text-sm {
  font-size: 13px;
}
.text-gray-500 {
  color: var(--el-text-color-secondary);
}
.option-item {
  display: inline-block;
}

.option-label {
  display: block;
  font-size: 14px;
}

.option-desc {
  display: block;
  font-size: 13px;
  color: var(--el-text-color-secondary);
  margin-top: 2px;
}
</style>
